package com.song.service.user;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.song.common.Result;
import com.song.dao.role.UserRoleDao;
import com.song.dao.user.UserDao;
import com.song.entity.user.User;
import com.song.util.ComUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao,User> implements UserService  {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserRoleDao userRoleDao;

    /**
     * 获得用户列表
     */
    @Override
    public Result<List<User>> queryUserList(String account, String name, String phone, int pageNum, int pageSize) {
        Result<List<User>> result = new Result<>();

        Map<String,Object> map = new HashMap<>();

        map.put("account", ComUtil.handleTrim(account));
        map.put("name",ComUtil.handleTrim(name));
        map.put("phone",ComUtil.handleTrim(phone));

        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userDao.queryUserList(map);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        result.setCode(0);
        result.setCount((int)pageInfo.getTotal());
        result.setData(userList);
        return result;
    }

    /**
     * 根据用户ID删除用户
     */
    @Override
    public Result<Integer> deleteUserById(int id) {
        Result<Integer> result = new Result<>();
        userRoleDao.deleteById(id);
        userDao.deleteUserById(id);
        result.setCode(0);
        return result;
    }

    /**
     * 新增用户
     */
    @Override
    public Result<Integer> addUser(User user) {
        Result<Integer> result = new Result<>();
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setCreateAdmin("admin");
        userDao.addUser(user);
        result.setCode(0);
        return result;
    }

    @Override
    public Result<Integer> batchDel(String[] ids) {
        Result<Integer> result = new Result<>();
        userDao.batchDel(ids);
        result.setCode(0);
        return result;
    }

    @Override
    public Result<Integer> updateUserName(String name, int id) {
        Result<Integer> result = new Result<>();
        userDao.updateUserName(name,id);
        result.setCode(0);
        return result;
    }

    @Override
    public Result<Integer> updateUser(User user) {
        Result<Integer> result = new Result<>();
        user.setUpdateAdmin("admin");
        userDao.updateUser(user);
        result.setCode(0);
        return result;
    }
}
